package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.article.feign.ArticleClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Transactional
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async
    @GlobalTransactional
    public void autoScanWmNews(Integer id) throws Exception {
        //1.校验参数
        WmNews wmNews = wmNewsMapper.selectOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        if (null == wmNews) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断传递过来的文章的状态是待审核的才审核
        if (wmNews.getStatus() == WmNews.Status.SUBMIT.getCode()) {
            //1.5.将文本和图片的信息抽取出来
            Map<String, Object> maps = handleTextAndImages(wmNews);
            //1.6自管理的敏感词过滤
            Boolean isSensitive = handleSensitiveScan(maps.get("text").toString(), wmNews);
            if (!isSensitive) {
                return;
            }
            //2.审核文本
            Boolean scan = handleTextScan(maps.get("text").toString(), wmNews);
            if (!scan) {
                return;
            }
            //3.审核图片
            Boolean imageScan = handleImageScan((List<String>) maps.get("image"), wmNews);
            if (!imageScan) {
                return;
            }
            //4.数据同步
            ResponseResult result = saveArticle(wmNews);
            //5.更新news的状态
            if (result.getCode() == 200) {
              /*    //-------------自定义异常---------
                  int a=1/0;
                  //-------------自定义异常---------*/
                wmNews.setArticleId((Long) result.getData());//回填一个Article 的Id,代表这是哪篇文章
                updateWmNews(wmNews, (short) 9, "审核通过,发布成功");
            } else {
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
            }
        }
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {

        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 1.6审核自管理的敏感词库
     *
     * @param text   抽取出的文本信息
     * @param wmNews 修改wmnews的状态
     * @return
     */
    private Boolean handleSensitiveScan(String text, WmNews wmNews) {
        //List<String> list = Arrays.asList(text.split(","));
/*        Boolean flag = true;
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> collect = wmSensitives.stream().map(wmSensitive -> wmSensitive.getSensitives()).collect(Collectors.toList());
        SensitiveWordUtil.initMap(collect);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (null != map && map.size() > 0) {
            //给wmnew对象设置状态,审核不通过
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"文本中包含有敏感词,审核不通过");
            flag = false;
        }
        return flag;*/
        Boolean flag=true;
        //处理出我们只要敏感词的那一行数据
        List<WmSensitive> sensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
       //将WmSensitive类型的集合转换成String类型的
        List<String> list = sensitiveList.stream().map(item -> item.getSensitives()).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(list);
        //审核内容中是否包含自管理的敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (map.size()>0&&null!=map){
             updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"当前文章中存在违规内容"+map);
            flag=false;
        }
        return flag;
    }

    /**
     * 4.数据同步到app端
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveArticle(WmNews wmNews) {
        /*ArticleDto dto = new ArticleDto();
        //复制属性
        BeanUtils.copyProperties(wmNews,dto);
        //处理基础属性
        dto.setLayout(wmNews.getType());
        dto.setCreatedTime(new Date());
        dto.setViews(0);
        if (null!=wmNews.getArticleId()){
            dto.setId(wmNews.getArticleId());
        }
        //处理作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        if (null!=wmNews.getUserId()){
            WmUser wmUser = wmUserMapper.selectOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getId, wmNews.getUserId()));
            if (null!=wmUser){
                dto.setAuthorName(wmUser.getName());
            }
        }
        //处理频道
        if (null!=wmNews.getChannelId()){
            WmChannel wmChannel = wmChannelMapper.selectOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getId, wmNews.getChannelId()));
            dto.setChannelName(wmChannel.getName());
        }*/
        ArticleDtoBuilder builder = new ArticleDtoBuilder(wmNews, wmChannelMapper, wmUserMapper);
        ArticleDto dto = builder
                .buildBeanCopy()
                .buildBasic()
                .buildAuthor()
                .buildChannel()
                .bulid();
        ResponseResult result = iArticleClient.saveArticle(dto);
        return result;
    }

    /**
     * 3.审核图片是否违规
     *
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        Boolean flag = true;
        if (null == images && images.size() == 0) {
            return flag;
        }
        List<byte[]> list = new ArrayList<>();
        List<String> collect = images.stream().distinct().collect(Collectors.toList());
        for (String img : collect) {
            byte[] bytes = fileStorageService.downLoadFile(img);
            //使用上面的minio下载的字节,创建一个ByteArrayInputStream,将字节放进
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            //使用ImageIO.read拿到一个BufferedImage
            BufferedImage image = ImageIO.read(in);
            //调用tess4jClient.doOCR(image).得到的就是识别图片中的文字,并返回成字符串了.
            String result = tess4jClient.doOCR(image);
            flag = handleSensitiveScan(result, wmNews);
            if (!flag) {
                return flag;
            }
            list.add(bytes);
        }

        Map map = greenImageScan.imageScan(list);
        if (null != map) {
            if ("block".equals(map.get("suggestion"))) {
                updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片包含违规内容");
               /* wmNews.setStatus(WmNews.Status.FAIL.getCode());
                wmNews.setReason("图片包含违规内容");
                wmNewsMapper.updateById(wmNews);*/
                flag = false;

            } else if ("review".equals(map.get("suggestion"))) {
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片包含不确定性因素,转人工审核");
                /*wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                wmNews.setReason("图片包含不确定性因素,转人工审核");
                wmNewsMapper.updateById(wmNews);*/
                flag = false;
            }/*else {
                flag=false;
                updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(),"审核通过");
              *//*  wmNews.setStatus(WmNews.Status.SUCCESS.getCode());
                wmNews.setReason("审核成功");
                wmNewsMapper.updateById(wmNews);*//*
            }*/
        } else {
            flag = false;
        }
        return flag;
    }

    /**
     * 2.对文章的内容进行审核,对文章的状态进行修改和设值
     *
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean handleTextScan(String text, WmNews wmNews) throws Exception {
        Boolean flag = true;
        if (org.apache.commons.lang.StringUtils.isBlank(text)) {
            return flag;
        }
        Map map = greenTextScan.greeTextScan(text);
        if (null != map) {
            if ("block".equals(map.get("suggestion"))) {
                updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "内容包含违规内容");
                 /*wmNews.setStatus(WmNews.Status.FAIL.getCode());
                 wmNews.setReason("内容包含违规内容");
                    wmNewsMapper.updateById(wmNews);*/
                flag = false;

            } else if ("review".equals(map.get("suggestion"))) {
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "内容包含不确定性因素,转人工审核");
                 /*   wmNews.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
                    wmNews.setReason("内容包含不确定性因素,转人工审核");
                    wmNewsMapper.updateById(wmNews);*/
                flag = false;
            } else {
                updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "审核通过");
                    /*wmNews.setStatus(WmNews.Status.SUCCESS.getCode());
                    wmNews.setReason("审核成功");
                    wmNewsMapper.updateById(wmNews);*/
            }
        }
        return flag;
    }

    /**
     * 1.5处理文章中的内容和图片以及封面中的图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        if (StringUtils.isBlank(wmNews.getContent())) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String content = wmNews.getContent();
        List<Map> maps = JSON.parseArray(content, Map.class);
        List<String> images = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (Map map : maps) {
            if ("text".equals(map.get("type"))) {
                sb.append(map.get("value"));
            } else if ("image".equals(map.get("type"))) {
                images.add(map.get("value").toString());
            }
        }
        if (StringUtils.isNotBlank(wmNews.getImages())) {//处理文章中的封面图片
            images.addAll(Arrays.asList(wmNews.getImages().split(",")));
        }
        //处理标题中的文字
        sb.append("-").append(wmNews.getTitle());
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("text", sb);
        stringObjectMap.put("image", images);
        return stringObjectMap;
    }
}
